package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.patterns.IToken;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter{
    @Override
    //返回过滤器类型 pre routing post error
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    //每个过滤器中默认过滤器的顺序号
    // 每个过滤器有五个默认的过滤器,自己的过滤器放在末尾
    public int filterOrder() {
        return 6;
    }

    @Override
    //针对当前请求,判断是否执行过滤代码
    public boolean shouldFilter() {
        //获取上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //当前请求,调用的服务id
        String serviceId = (String)
                ctx.get(FilterConstants.SERVICE_ID_KEY);
        //当前请求,调用的服务id
        return "item-service".equals(serviceId);
    }

    @Override
    //过滤代码
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext stx = RequestContext.getCurrentContext();
        //获得request对象
        HttpServletRequest request = stx.getRequest();
        //http://localhost:3001/item-service/kjdflksj?token=sjhfk
        //接收token参数
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应
        if (StringUtils.isBlank(token)){
            //阻止调用
            stx.setSendZuulResponse(false);//禁止发送zuul响应
            //直接返回响应
            //JsonResult --- {code:1,msg:xxx,data:}
            stx.addZuulResponseHeader(
                    "Content-Type","application/json;charset=UTF-8");//返回的响应头
            stx.setResponseBody(JsonResult
                                .err()
                                .code(400)
                                .msg("not login")
                                .toString());
        }
        return null;//当前zuul版本中,这个返回值不起作用
    }
}
